﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.Composition;
using System.Xml.Linq;
using System.IO;

namespace Kindler.Processors
{
    [Export(typeof(IProcessor))]
    public class CodeBlockProcessor : IProcessor
    {
        public void Process(XDocument htmlBook)
        {
            var codeBlocks = from XElement pre in htmlBook.Descendants("pre")
                             select pre;

            foreach (var block in codeBlocks)
            {
                string line;
                var newContent = new List<XElement>();

                using (var reader = new StringReader(block.Value))
                {
                    while ((line = reader.ReadLine()) != null)
                    {
                        var newLine = new XElement("p", new XElement("code", line));
                        newLine.Add(new XAttribute("width", string.Format("{0}em", GetNumberOfIndents(line) * 2)));

                        newContent.Add(newLine);
                    }
                }

                block.Value = string.Empty; // Empty text - we're about to replace the value
                block.Add(newContent);
                block.Name = "div"; // Rename to <div> because kindle doesn't understand <pre>
                // Add some spacing each above and below
                block.AddBeforeSelf(new XElement("br"));
                block.AddAfterSelf(new XElement("br"));
            }
        }

        private static int GetNumberOfIndents(string line)
        {
            int spaces = 0;

            foreach (char c in line)
            {
                if (char.IsWhiteSpace(c))
                {
                    spaces++;
                }
                else
                {
                    break;
                }
            }

            return spaces / 4;
        }
    }
}